package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.dialog.AppLoading;
import com.superfish.cutieshop.utils.BitmapUtils;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.ImageConfig;
import com.superfish.cutieshop.utils.MD5Utils;
import com.superfish.cutieshop.utils.MessageHandlerList;
import com.superfish.cutieshop.utils.SimpleAsync;
import com.superfish.cutieshop.utils.TimeUtils;
import com.superfish.cutieshop.view.photoview.PhotoView;

@ContentView(R.layout.activity_croper)
public class CroperActivity extends BaseActivity {

    @ViewInject(R.id.toolbar)
    private Toolbar mToolbar;

    public static void open(Activity act, String path) {
        Intent i = new Intent(act, CroperActivity.class);
        i.putExtra("path", path);
        open(act, i);
    }

    @ViewInject(R.id.croperImagePv)
    private PhotoView mPhotoView;
    private String path;

    private AppLoading mloading;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mloading = new AppLoading(this);
        path = getIntent().getStringExtra("path");
        mToolbar.setTitle("");
        setAppTitle("裁剪头像");
        mToolbar.setNavigationIcon(R.drawable.btn_back_bar);
        //动态设置颜色 根据当前星期时间设置
        mToolbar.setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        getStatusBar().setBackgroundColor(getResources().getColor(TimeUtils.aTheme()));
        setSupportActionBar(mToolbar);
        ImageLoader.getInstance().clearMemoryCache();
        // 1:1 裁切 --
        ViewGroup.LayoutParams params = mPhotoView.getLayoutParams();
        int w = CommonUtil.getWindowWidth(CroperActivity.this);
        params.width = w;
        params.height = params.width;
        mPhotoView.setLayoutParams(params);
        ImageLoader.getInstance().displayImage("file:///" + path, mPhotoView, ImageConfig.getPhotoOptions());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_register2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_share) {
            //完成裁剪操作
            // 获取Bitmap 存储 然后清空Bit 关闭所有界面
            new SimpleAsync(new SimpleAsync.SimpleCallback() {
                private String bitstr;

                @Override
                public void onStart() {
                    Bitmap bit = clipHeader();
                    bitstr = BaseApp.getTempCache(CroperActivity.this) + "/"
                            + createFileName(path);
                    BitmapUtils.saveImage(bitstr, bit);
                    bit.recycle();
                }

                @Override
                public void onPrepare() {
                    mloading.show();
                }

                @Override
                public void onFinish() {
                    mloading.dismiss();
                    //结束 -- 传给相应的界面 --
                    //返回结果
                    MessageHandlerList.sendMessage(PhotoActivity.class, BaseConfig.MessageCode.CROPER, bitstr);
                    MessageHandlerList.sendMessage(EditPersonActivity.class, BaseConfig.MessageCode.CROPER, bitstr);
                    MessageHandlerList.sendMessage(Register2Activity.class, BaseConfig.MessageCode.CROPER, bitstr);
                    CroperActivity.this.finish();
                }
            }).execute();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 获取文件后缀名
     *
     * @return
     * @method
     */
    public static String getFileSuffix(String url) {
        String prefix = url.substring(url.lastIndexOf("."));
        return prefix;
    }

    /**
     * 创建文件名字
     *
     * @param url 网络Url
     * @return
     */
    public static String createFileName(String url) {
        // ----统一命名规则
        try {
            String suffix = getFileSuffix(url);
            return MD5Utils.toMD5(url) + suffix;
        } catch (Exception e) {
            return MD5Utils.toMD5(url);
        }

    }


    /**
     * 裁减头像
     **/
    public Bitmap clipHeader() {
        mPhotoView.setDrawingCacheEnabled(true);
        Bitmap snapshot = mPhotoView.getDrawingCache();
        getSendCanvas().setBitmap(getSendBmp());
        getSendCanvas().drawBitmap(
                snapshot,
                new Rect(0, 0, snapshot.getWidth(), snapshot.getHeight()),
                new Rect(0, 0, getSendBmp().getWidth(), getSendBmp()
                        .getHeight()), getPaint());
        mPhotoView.destroyDrawingCache();
        return getSendBmp();
    }

    Canvas mSendCanvas = null;

    /**
     * 获取发布画布
     **/
    protected Canvas getSendCanvas() {
        if (mSendCanvas == null)
            mSendCanvas = new Canvas();
        return mSendCanvas;
    }

    /**
     * 获取发布图片
     **/
    Bitmap mSendBmp = null;

    /**
     * 获取背景宽高
     **/
    protected Bitmap getSendBmp() {
        if (mSendBmp == null)
            mSendBmp = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888);
        return mSendBmp;
    }

    /**
     * 获取画笔
     **/
    Paint mPaint = null;

    protected Paint getPaint() {
        if (mPaint == null) {
            mPaint = new Paint();
            // 设置抗锯齿，三者必须同时设置效果才可以
            mPaint.setAntiAlias(true); // 等同于mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
            mPaint.setFilterBitmap(true);
            mPaint.setDither(true);
        }
        return mPaint;
    }

}
